package cn.vendsystem.com.AOP;

import cn.vendcommon.com.entity.User;
import cn.vendcommon.com.entity.constants.CommonCodeMsg;
import cn.vendcommon.com.exception.VendException;
import cn.vendcommon.com.utils.UserContext;
import cn.vendsystem.com.service.UserService;
import io.minio.http.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AuthAspect {

    @Autowired
    private UserService userService;

    @Before("@annotation(adminCheck)")
    public void checkAdminRole(JoinPoint joinPoint, AdminCheck adminCheck) throws Exception {
        // 取注解里的参数名
        String paramName = adminCheck.value();

        // 拿到方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames = signature.getParameterNames();
        Object[] args = joinPoint.getArgs();

        // 找到对应的参数值
        String phone = null;
        for (int i = 0; i < parameterNames.length; i++) {
            if (parameterNames[i].equals(paramName)) {
                phone = args[i].toString();
                break;
            }
        }

        if (phone == null || phone.isBlank()) {
            throw new Exception("未获取到 phone 参数");
        }

        int role = userService.getRoleByPhone(phone);

        // role = 0 表示管理员
        if (role != 0) {
            throw new VendException(CommonCodeMsg.NO_PERMISSION);
        }
    }
}
